package com.ktjiaoyu.ktmall.servlet.api;

import com.alibaba.fastjson.JSON;
import com.ktjiaoyu.ktmall.entity.Product;
import com.ktjiaoyu.ktmall.service.ProductService;
import com.ktjiaoyu.ktmall.service.impl.ProductServiceImpl;
import com.ktjiaoyu.ktmall.utils.Page;
import com.ktjiaoyu.ktmall.utils.R;
import com.ktjiaoyu.ktmall.utils.RequestUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.Map;

@WebServlet(name = "ProductServlet", urlPatterns = "/api/product/*")
public class ProductServlet extends HttpServlet {
    private final ProductService productService = new ProductServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 统一设置编码
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");
        req.setCharacterEncoding("utf-8");

        String path = req.getPathInfo();
        PrintWriter out = resp.getWriter();
        R result = null;

        try {
            if (path == null || "/list".equals(path)) {
                // 处理列表查询
                String title = req.getParameter("title");
                Long categoryId = RequestUtil.parseLong(req, "categoryId", null);
                Integer pageNo = RequestUtil.parseInt(req, "pageNo", 1);
                Integer pageSize = RequestUtil.parseInt(req, "pageSize", 10);
                Page<Product> list = productService.findList(title, categoryId, pageNo, pageSize);
                result = R.ok(list);
            } else if (path.matches("/\\d+")) {
                // 处理单个商品查询
                Long id = Long.valueOf(path.substring(1));
                Product product = productService.findById(id);
                result = product != null ? R.ok(product) : R.fail();
            } else {
                // 无效路径
                result = R.fail("无效的请求路径");
            }
        } catch (SQLException e) {
            result = R.fail("服务器异常：" + e.getMessage());
            e.printStackTrace();
        }

        // 输出响应（不手动关闭流，由容器管理）
        out.print(JSON.toJSONString(result));
        out.flush();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 统一设置编码
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");
        req.setCharacterEncoding("utf-8");

        PrintWriter out = resp.getWriter();
        R result = null;

        try {
            // 读取请求体（只读取一次）
            BufferedReader reader = req.getReader();
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            // 解析JSON为Product对象
            Product product = JSON.parseObject(sb.toString(), Product.class);

            // 处理保存/更新
            boolean success = productService.saveOrUpdate(product);
            result = success ? R.ok() : R.fail("保存失败");
        } catch (SQLException e) {
            result = R.fail("服务器异常：" + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            result = R.fail("请求解析失败：" + e.getMessage());
            e.printStackTrace();
        }

        // 输出响应（不手动关闭流，由容器管理）
        out.print(JSON.toJSONString(result));
        out.flush();
    }

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");
        req.setCharacterEncoding("utf-8");
        String path = req.getPathInfo();
        PrintWriter out = resp.getWriter();

        if (path != null && path.matches("/\\d+")){
            Long id = Long.valueOf(path.substring(1));
            try {
                boolean success = productService.removeById(id);
                R result = success ? R.ok() : R.fail("删除失败");
                out.print(JSON.toJSONString(result));
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");
        req.setCharacterEncoding("utf-8");
        String path = req.getPathInfo();
        PrintWriter out = resp.getWriter();
        if (path != null && path.matches("/\\d+/status")){
            Long id = Long.valueOf(path.split("/")[1]);
            BufferedReader reader = req.getReader();
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            Map<String,Object> map = JSON.parseObject(sb.toString(), Map.class);
            Integer status = (Integer) map.get("status");
            try {
                boolean success = productService.updateStatus(id, status);
                R result = success ? R.ok() : R.fail("更新失败");
                out.print(JSON.toJSONString(result));
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }else {
            out.print(R.fail("无效的请求路径"));
        }
    }
}
